from pathlib import Path

import pytest, requests, time, json, os
from utils.logger_util import Logger
from utils.yaml_util import read_yaml

TOKEN_FILE = "/tmp/access_token.json"  # 存放 access_token 的临时文件路径


@pytest.fixture(scope="module")
def access_token(wechat_base_url):
    """
    从临时文件获取或刷新 access_token
    """
    logger = Logger().get_logger()

    # 检查文件是否存在
    if os.path.exists(TOKEN_FILE):
        # 文件存在，尝试读取
        with open(TOKEN_FILE, "r") as f:
            try:
                token_data = json.load(f)
            except json.JSONDecodeError:
                token_data = {}

        # 检查 token 是否有效
        if "access_token" in token_data and "expire_time" in token_data:
            current_time = time.time()
            # print(current_time - token_data["expire_time"])
            if current_time - token_data["expire_time"] < 300:
                logger.info(f"使用缓存的 access_token: {token_data['access_token']}")
                return {"access_token": token_data["access_token"]}

    # 文件不存在或 token 无效，重新请求 access_token
    logger.info("缓存的 access_token 无效或不存在，重新获取")

    # 读取 API 请求参数
    case_data = read_yaml(Path(__file__).parents[1] /
                          "data/wechat/access_token/get_access_token.yaml"
                          )['test_cases'][0]
    url = wechat_base_url + case_data["request"]["url"]
    method = case_data["request"]["method"]
    params = case_data["params"]

    # 发送请求获取 access_token
    response = requests.request(method=method, url=url, params=params)
    response_json = response.json()

    if "access_token" in response_json:
        access_token = response_json["access_token"]
        expire_time = time.time()

        # 存入临时文件
        with open(TOKEN_FILE, "w") as f:
            logger.info(f"重新写入缓存 access_token: {access_token}")
            json.dump({"access_token": access_token, "expire_time": expire_time}, f)

        return {"access_token": access_token}
    else:
        pytest.fail(f"获取 access_token 失败: {response_json}")


if __name__ == '__main__':
    print(Path(__file__).parents[1])
